﻿using Microsoft.AspNetCore.Mvc;
using Sprout.Cache.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Sprout.Api.Test.Controllers
{
    public class RedisController: ApiControllerBase
    {

        /// <summary>
        /// 锁测试同步
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object LockTest1()
        {
            string lockKey = "lockKey";
            string result = string.Empty;
            //Task.Run(() =>
            //{
            //    for (int i = 0; i < 30; i++)
            //    {
            //        Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId.ToString() },正在执行，值：{i}，时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}");
            //        Thread.Sleep(500);
            //    }
            //});

            RedisService.Lock(lockKey, () =>
            {
                Thread.Sleep(5000);

                result = Guid.NewGuid().ToString();
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId.ToString() },锁的实际方法执行完成,{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");
            });

            return result;
        }

        /// <summary>
        /// 锁测试异步
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> LockTest2()
        {
            string lockKey = "lockKey";
            string result = string.Empty;

            //Task.Run(async () =>
            //{
            //    for (int i = 0; i < 30; i++)
            //    {
            //        Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId.ToString() },正在执行，值：{i}，时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}");
            //        Thread.Sleep(500);
            //    }
            //});

            await RedisService.LockAsync(lockKey, async () =>
            {
                Thread.Sleep(5000);

                result = Guid.NewGuid().ToString();
                Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId.ToString() },锁的实际方法执行完成,{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");
            });

            return result;
        }
        /// <summary>
        /// 批量匹配删除key
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public void KeysDelete(int count)
        {
            string p = "DelKeysTest:";
            var client = RedisService.GetRedisClientFirst();
            for (var i = 0; i < count; i++)
            {
                client.Set(p + i, "i");
            }

            RedisService.DelByPattern(client, "*DelKeysTest*");

        }
    }
}
